package com.myblog.Utils;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName : OssUtil
 * @Description :
 * @Author : CJH
 * @Date: 2021-01-07 14:59
 */
public class AliOssUtil {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private static String accessKeyId = "LTAI5tMNo34PTGVmVnsErjJg";
    private static String accessKeySecret = "9y6vEJeoZPzejLHP01qNsVwuoERVJl";

    private static String  bucketName = "xiaop-bucket";
    private static OSS ossClient = null;

    private AliOssUtil(){}


    public static URL UpLoadAvatar(MultipartFile file,String ossPath) throws IOException {
        if(Objects.isNull(ossClient)) {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        }

        InputStream inputStream=file.getInputStream();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, ossPath,inputStream);
        ossClient.putObject(putObjectRequest);
        inputStream.close();
        return getUrl(ossPath);
    }
    public static URL getUrl(String ossPath){
        Date expiration = new Date(new Date().getTime() + 3600 * 30000);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, ossPath, expiration);
        return url;
    }
}

